<template>
  <div class="calendar">
    <van-field :readonly="element.readonly" :disabled="element.disabled" :required="element.required" clickable name="calendar" :value="value" :label="element.label" :placeholder="element.placeholder" @click="showCalendar = true" />
    <van-calendar :color="element.style.color" :default-date="defaultDate" :type="type" v-model="showCalendar" @confirm="onConfirm" :min-date="minDate" :max-date="maxDate" :position="element.position" :max-range="element.maxRange" />
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'calendarItem',
  inject: ['element'],
  data() {
    return {
      value: '',
      showCalendar: false,
      defaultDate: dayjs().toDate(),
      minDate: dayjs().toDate(),
      maxDate: dayjs().add(1, 'month').toDate()
    }
  },
  computed: {
    type() {
      return this.element.dateType
    },
    vModel() {
      return this.element.vModel
    }
  },
  watch: {
    vModel: {
      handler(val) {
        this.value = val
      },
      immediate: true
    },
    showCalendar(val) {
      if (val) {
        /**
         * 回显
         */
        if (this.type === 'single') {
          // 单个日期
          this.defaultDate = this.vModel === '' ? dayjs().toDate() : dayjs(this.vModel).toDate()
        } else if (this.type === 'range') {
          // 区间日期
          const dateArr = this.vModel.split('至')
          // 当天和第二天
          const today = dayjs().toDate()
          const tomorrow = dayjs().add(1, 'day').toDate()
          this.defaultDate = this.vModel === '' ? [today, tomorrow] : [dayjs(dateArr[0]).toDate(), dayjs(dateArr[1]).toDate()]
        }
        /**
         * 选择范围控制
         */
        // console.log(this.element.minDate, this.element.maxDate, '==this.element.maxDate==')
        this.minDate = dayjs(this.element.rangeDate[0]).toDate()
        this.maxDate = dayjs(this.element.rangeDate[1]).toDate()
      }
    }
  },
  methods: {
    onConfirm(date) {
      // 单选
      if (this.type === 'single') {
        this.value = dayjs(date).format(this.element.format)
      } else if (this.type === 'range') {
        this.value = dayjs(date[0]).format(this.element.format) + '至' + dayjs(date[1]).format(this.element.format)
      }
      this.$emit('onConfirm', this.value)
      this.showCalendar = false
    }
  }
}
</script>

<style lang="scss" scoped>
.van-cell:last-child::after {
  display: block;
}
</style>